<template>
  <div>
    <el-row :gutter="10" v-if="type">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:project:payment:add']"
            @click="handleAdd(null)">增加</el-button>
          <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:project:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
    </el-row>

    <div class="grid-content bg-purple text">
      <span>总回款比例：{{ amount }}%</span>
    </div>

    <el-table v-loading="loading" :data="paymentList" highlight-current-row max-height="300"
      v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
      <el-table-column type="index" label="序号" align="center" width="50">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="projectName" label="项目名称" align="center" />
      <el-table-column prop="type" label="回款属性" align="center" />
      <el-table-column prop="paymentAmount" label="回款金额(元)" align="center" />
      <el-table-column prop="paymentRatio" label="回款比例(%)" align="center" />
      <el-table-column prop="paymentDate" label="回款日期" align="center" />
      <el-table-column prop="expireDate" label="质保金到期日期" align="center" />
      <el-table-column property="createBy" label="创建人" align="center" />
      <el-table-column property="createTime" label="创建时间" align="center" sortable />
      <el-table-column prop="remark" label="备注" align="center" />
      <el-table-column label="操作" align="center"
        v-if="type && ($auth.hasPermi('md:project:payment:remove') || $auth.hasPermi('md:project:payment:edit'))">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['md:project:payment:edit']"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
            @confirm="handleDelete(scope.row)">
            <el-button size="mini" type="text" icon="el-icon-delete" v-hasPermi="['md:project:payment:remove']"
              slot="reference" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 表单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" :fullscreen="device == 'mobile'">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px"
        :label-position="device == 'mobile' ? 'top' : 'right'">
        <el-form-item label="回款属性" prop="type">
          <el-select v-model="form.type" filterable clearable placeholder="请选择回款属性" style="width: 100%;">
            <el-option v-for="item in collectionType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item> -->
        <el-form-item label="回款金额" prop="paymentAmount">
          <el-input v-model="form.paymentAmount" type="number" placeholder="请输入回款金额" @blur="blurHandler">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="回款比例" prop="paymentRatio">
          <el-input v-model="form.paymentRatio" placeholder="请输入回款比例" disabled>
            <template slot="prepend" v-if=" form.type === '付质保金'">-</template>
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="回款日期" prop="paymentDate">
          <el-date-picker v-model="form.paymentDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="质保金到期" prop="expireDate">
          <el-date-picker v-model="form.expireDate" type="date" value-format="yyyy-MM-dd" placeholder="选择质保金到期日期"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注"
            :autosize="{ minRows: 2 }" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProjectPayment, insertProjectPayment, updateProjectPayment, deleteProjectPayment } from "@/api/crm/sa/payment";
import { getUserProfile } from "@/api/system/user";
import { mapGetters } from 'vuex'

export default {
  name: "ProjectPayment",
  data() {
    return {
      // 总回款比例
      amount: "",
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目回款表格数据
      paymentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      queryParams: {
        projectName: "",
        projectId: null,
        userId: null,
        deptId: null,
        paymentDate: null,
        pageNum: 1,
        pageSize: 10
      },
      // 表单数据
      form: {
        id: null,
        projectId: null,
        userId: null,
        deptId: null,
        paymentAmount: null,
        paymentRatio: null,
        paymentDate: null,
        type: "回货款",
        expireDate: null,
        remark: null
      },
      // 表单验证
      rules: {
        type: [
          { required: true, message: "请选择回款属性", trigger: "change" }
        ],
        projectId: [
          { required: true, message: "项目ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        paymentAmount: [
          { required: true, message: "回款金额不能为空", trigger: "blur" }
        ],
        paymentDate: [
          { required: true, message: "回款日期不能为空", trigger: "blur" }
        ]
      },
      // 回款属性
      collectionType: [
        {
          label: "回货款",
          value: "回货款",
        },
        {
          label: "付质保金",
          value: "付质保金",
        },
        {
          label: "退质保金",
          value: "退质保金",
        }
      ],
      // 加载状态
      submitting: false,
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    };
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  props: {
    projectInfo: {
      type: Object,
      required: true,
    },
    type: {
      type: Number,
      default: 1, // 1是全部功能 0是仅查看
    },
    change: {
      type: Function,
      default: () => { }
    },
  },
  watch: {
    projectInfo: {
      deep: true,
      immediate: true,
      handler(newV) {
        this.queryParams.projectId = newV.id
        this.form.projectName = newV.name
        this.form.projectId = newV.id
        this.handleQuery()
      },
    },
  },
  created() {
    this.getUserinfo()
    // this.getList();
  },
  methods: {
    // 计算汇款比例
    blurHandler() {
      const num = this.form.paymentAmount / (this.projectInfo.bidAmount * 10000)
      this.form.paymentRatio = +((Math.floor(num * 100) / 100) ?? 0) * 100
      // this.form.paymentRatio = +(num.toFixed(2) ?? 0) * 100
    },
    /** 查询项目回款列表 */
    getList() {
      this.loading = true;
      listProjectPayment(this.queryParams).then(response => {
        this.paymentList = response.rows;
        this.amount = response.amount ?? 0;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.resetForm("queryForm");
      this.getList();
    },
    /** 新增项目回款 */
    handleAdd() {
      this.formId && this.resetForm("form");
      this.formId = null
      this.open = true;
      this.title = "新增项目回款";
    },
    /** 修改项目回款 */
    handleUpdate(row) {
      this.resetForm("form");
      this.form = { ...row };
      this.formId = row.id
      // const params = { id: row.id };
      // getProjectPayment(params).then(response => {
      // this.form = response.data;
      this.open = true;
      this.title = "修改项目回款";
      // });
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitting = true;
          this.form.paymentRatio = this.form.type === '付质保金' ? -1 * (this.form.paymentRatio) : this.form.paymentRatio
          if (this.form.id != null) {
            updateProjectPayment({
              ...this.form,
              updateBy: this.user.nickName,
            }).then(res => {
              this.submitting = false;
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.getList();
                this.open = false
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
              }
            });
          } else {
            insertProjectPayment({
              ...this.form,
              createBy: this.user.nickName,
              updateBy: this.user.nickName,
              userId: this.user.userId,
            }).then(res => {
              this.submitting = false;
              if (res.code === 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.getList();
                this.open = false
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
              }
            });
          }
        }
      });
    },
    /** 删除项目回款 */
    handleDelete(row) {
      // this.$confirm('是否确认删除项目回款编号为"' + row.id + '"的数据?', "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => {
      deleteProjectPayment(row).then(res => {
        this.submitting = false;
        if (res.code === 200) {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.getList();
          this.open = false
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      });
      // });
    },
    /** 取消操作 */
    cancel() {
      this.open = false;
      // this.resetForm("form");
    }
  }
};
</script>

<style lang="scss" scoped>
.grid-content.text{
  margin-top: 10px;
  color: red;
}
</style>
